﻿class Boid {
    Position: CPosition;
    Speed: number;
    Direction: CDirection;
 

    Neighbours: Array<Boid>;
    private distancesToNeighbours: Array<number>;
    constructor() {
        this.Position = new CPosition();
        this.Direction = new CDirection();
        this.Speed = Math.random() * 1;                  // <2
        
        this.Neighbours = new Array<Boid>(5);
        this.distancesToNeighbours = new Array<number>(5);

    }

    Move() {
        this.Position.Move(this.Direction, this.Speed);

        var seperationDirection = this.CalculateSeperationDirection();
        var alignmentDirection = this.CalculateAlignmentDirection();

        this.Direction.X = (alignmentDirection.X + this.Direction.X) / 2;
        this.Direction.Y = (alignmentDirection.Y + this.Direction.Y) / 2;

        //for (var i = 0; i < this.Neighbours.length; i++) {
        //    if (this.distancesToNeighbours[i] < 7)
        //        this.ChangeDirectionRandomly();
        //}


        


    }

    private CalculateSeperationDirection():CDirection {
 
        for (var i = 0; i < this.Neighbours.length; i++) {
            if (this.distancesToNeighbours[i] < 7)
                return new CDirection();    // random direction
        }
        return new CDirection(0, 0);
    }

    private CalculateAlignmentDirection(): CDirection {
        var retVal = new CDirection(0,0);
        for (var i = 0; i < this.Neighbours.length; i++) {
            retVal.X += this.Neighbours[i].Direction.X;
            retVal.Y += this.Neighbours[i].Direction.Y;
        }

        retVal.X /= this.Neighbours.length;
        retVal.Y /= this.Neighbours.length;

        return retVal;
    }

    CalculateNeighbours(swarm: Array<Boid>) {
   
        var sortedSwarm = swarm.slice().sort((b1, b2) => this.Distance(b1) - this.Distance(b2));
        for (var i = 0; i < 5; i++) {
            this.Neighbours[i] = sortedSwarm[i];
            this.distancesToNeighbours[i] = this.Distance(this.Neighbours[i]);
        }

    }

    private Distance(otherBoid: Boid): number {
        if (otherBoid == this)
            return 100;
        return this.Position.Distance(otherBoid.Position);

    }

 
} 